package com.sudo.service.admin.service.impl;

import com.github.pagehelper.PageHelper;
import com.sudo.common.enums.SysYesNo;
import com.sudo.common.utils.LocalDateTimeUtil;
import com.sudo.common.utils.PagedGridResult;
import com.sudo.dao.admin.entity.SysAutoRole;
import com.sudo.dao.admin.mapper.SysAutoRoleMapper;
import com.sudo.dao.admin.model.bo.SysAutoRoleQueryBO;
import com.sudo.dao.admin.model.bo.SysAutoRoleUpdateBO;
import com.sudo.dao.admin.model.vo.SysAutoRoleVO;
import com.sudo.dao.admin.model.vo.SysUserReVO;
import com.sudo.service.admin.service.AdminBaseService;
import com.sudo.service.admin.service.SysAutoRoleService;
import com.sudo.service.admin.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class SysAutoRoleServiceImpl extends AdminBaseService implements SysAutoRoleService {


    @Resource
    private SysAutoRoleMapper sysAutoRoleMapper;

    @Resource
    private SysUserService sysUserService;

    @Transactional(propagation = Propagation.SUPPORTS,rollbackFor = Exception.class)
    @Override
    public PagedGridResult queryAutoRoleByPage(SysAutoRoleQueryBO sysAutoRoleQueryBO) {
        PageHelper.startPage(sysAutoRoleQueryBO.getPage(), sysAutoRoleQueryBO.getPageSize());
        List<SysAutoRoleVO> autoRoleInfo = sysAutoRoleMapper.getAutoRoleInfo(sysAutoRoleQueryBO);
        LocalDateTime nowTime = LocalDateTime.now().withSecond(0);
        for (SysAutoRoleVO sysAutoRoleVO : autoRoleInfo) {
            LocalDateTime expirationTime = sysAutoRoleVO.getExpirationTime();
            String dayHourMin = LocalDateTimeUtil.calculateDayHourMin(nowTime, expirationTime);
            sysAutoRoleVO.setRemainingTime(dayHourMin);
        }
        return setterPagedGrid(autoRoleInfo , sysAutoRoleQueryBO.getPage());
    }

    @Override
    public SysAutoRole getAutoRoleByUsername(String username) {
        Example example = new Example(SysAutoRole.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username", username);
        return sysAutoRoleMapper.selectOneByExample(example);
    }

    @Override
    public int updateAutoRole(SysAutoRoleUpdateBO sysAutoRoleUpdateBO, String status) {
        Example example = new Example(SysAutoRole.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username", sysAutoRoleUpdateBO.getUsername());
        SysAutoRole sysAutoRole = new SysAutoRole();
        sysAutoRole.setSetupRole(sysAutoRoleUpdateBO.getSetupRole());
        sysAutoRole.setExpiryRole(sysAutoRoleUpdateBO.getExpiryRole());
        LocalDateTime expirationTime = sysAutoRoleUpdateBO.getExpirationTime().withSecond(0);
        sysAutoRole.setExpirationTime(expirationTime);
        sysAutoRole.setStatus(sysAutoRoleUpdateBO.getStatus());

        // 修改过期时间的同时也要更新状态，过期时间比当前时间至少大5分钟
        LocalDateTime now = LocalDateTime.now();
        if (expirationTime.compareTo(now) > 0) {
            // 正常
            sysAutoRole.setIsExpired(SysYesNo.NO.name());
            // 更新角色权限
            sysUserService.updateSysUserRoleStatus(
                    sysAutoRoleUpdateBO.getUsername(),
                    sysAutoRoleUpdateBO.getSetupRole(),
                    status
            );
        }else {
            // 过期
            sysAutoRole.setIsExpired(SysYesNo.YES.name());
            // 更新角色权限
            sysUserService.updateSysUserRoleStatus(
                    sysAutoRoleUpdateBO.getUsername(),
                    sysAutoRoleUpdateBO.getExpiryRole(),
                    status
            );
        }

        return sysAutoRoleMapper.updateByExampleSelective(sysAutoRole,example);
    }

    @Override
    public List<SysAutoRole> getExpirationAutoRole() {
        Example example = new Example(SysAutoRole.class);
        Example.Criteria criteria = example.createCriteria();
        LocalDateTime nowTime = LocalDateTime.now();
        criteria.andLessThan("expirationTime", nowTime);
        return sysAutoRoleMapper.selectByExample(example);
    }

    @Override
    public int updateAutoRoleStatus(SysAutoRole autoRole) {
        Example example = new Example(SysAutoRole.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username", autoRole.getUsername());
        SysAutoRole sysAutoRole = new SysAutoRole();
        sysAutoRole.setIsExpired(SysYesNo.YES.name());
        SysUserReVO sysUserReVO = sysUserService.getSysUserAndRoleByUsername(autoRole.getUsername());
        int affectCount = 0;
        // 如果角色过期，并且当前角色 == 过期角色，则不执行，否则执行
        if (!(sysUserReVO.getRoleCode().equals(autoRole.getExpiryRole())
                && SysYesNo.YES.name().equals(autoRole.getIsExpired()))){
            affectCount = sysAutoRoleMapper.updateByExampleSelective(sysAutoRole, example);
            if (affectCount > 0){
                // 更新角色权限
                sysUserService.updateSysUserRoleStatus(
                        autoRole.getUsername(),
                        autoRole.getExpiryRole(),
                        sysUserReVO.getStatus()
                );
            }
        }
        return affectCount;
    }

    @Override
    public int getCountBySetupRole(String setupRole) {
        Example example = new Example(SysAutoRole.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("setupRole", setupRole);
        return sysAutoRoleMapper.selectCountByExample(example);
    }

    @Override
    public int getCountByExpiryRole(String expiryRole) {
        Example example = new Example(SysAutoRole.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("expiryRole", expiryRole);
        return sysAutoRoleMapper.selectCountByExample(example);
    }
}
